<template xmlns:text-align="http://www.w3.org/1999/xhtml">
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>报销补帖</el-breadcrumb-item>
      <el-breadcrumb-item>报销管理</el-breadcrumb-item>
      <el-breadcrumb-item><b>日常报销申请</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div style="margin:40px 20px 20px 20px">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="填报日期" prop="writedate">
        <el-date-picker clearable
                        v-model="searchFormModel.writedate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择填报日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-select v-model="searchFormModel.department" placeholder="请选择部门" clearable style="width: 130px">
          <el-option
              v-for="item in departmentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="state"><!--编制-->
        <el-select v-model="searchFormModel.state" placeholder="请选择审批状态" clearable style="width: 150px">
          <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="searchOnSubmit">查询</el-button>
        <el-button style="background-color: pink" @click="dialogAddState=true">添加</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!--  数据表格-->
  <div style="margin:20px">
    <el-table :data="blogInfo" stripe border style="width: 100%">
      <el-table-column label="填报日期" align="center" prop="writedate" width="180">
      </el-table-column>
      <el-table-column label="部门" align="center" prop="department" />
      <el-table-column label="报销事由" align="center" prop="reason" />
      <el-table-column label="报销金额" align="center" prop="money" />
      <!--      <el-table-column label="上传票据" align="center" prop="rill" width="100"/>-->
      <el-table-column label="上传票据" align="center" prop="rill" width="100">
        <template #default="scope">
          <el-image
              style="width: 50px;height: 50px;border-radius: 5px"
              :src="scope.row.rill"
          />
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="state">
        <template #default="scope">
          <span v-if="scope.row.state===0"><el-tag type="danger">已拒绝</el-tag></span>
          <span v-if="scope.row.state===1"><el-tag type="success">已通过</el-tag></span>
          <span v-if="scope.row.state===2"><el-tag type="danger">已驳回</el-tag></span>
          <span v-if="scope.row.state===3"><el-tag type="danger">已撤销</el-tag></span>
          <span v-if="scope.row.state===4"> <el-tag type="warning">审批中</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small"
                     :disabled="scope.row.state === 3 || scope.row.state === 1 || scope.row.state === 0 ||  scope.row.state === 4"
                     @click="tableEditHandler(scope.$index, scope.row) ">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              :disabled="scope.row.state === 3 || scope.row.state === 1 || scope.row.state === 0 ||  scope.row.state === 4"
              @click="tableDeleteHandler(scope.row.id)">
            <el-icon><Switch /></el-icon>撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--  分页-->
  <div class="page">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3,5]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 添加模态框 -->
  <el-dialog v-model="dialogAddState" title="添加日常报销申请" width="680">
    <div>
      <el-form ref="formAddRef" :model="formAdd" label-width="120px" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="writedate" label="填报日期">
              <el-date-picker clearable
                              v-model="formAdd.writedate"
                              type="date"
                              placeholder="请选择填报日期"
                              @change="formatDate1"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item prop="department" label="部门">
              <el-select v-model="formAdd.department" placeholder="请选择部门" clearable >
                <el-option label="人事部" value="人事部"></el-option>
                <el-option label="后勤部" value="后勤部"></el-option>
              </el-select>
              <!--              <el-input v-model="formAdd.department"></el-input>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="reason" label="报销事由" >
              <el-input v-model="formAdd.reason"  placeholder="请输入报销事由"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="money" label="报销金额">
              <el-input v-model="formAdd.money" placeholder="请输入报销金额"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-form-item prop="rill" label="上传票据">
            <!--              <el-input v-model="formAdd.rill"></el-input>-->
            <el-upload
                :action="'http://localhost:9095/upload'"
                :on-success="handleFiledUpload"
                :auto-upload="true"
                list-type="picture">
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>

        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddOnReset">取消</el-button>
        <el-button type="primary" @click="submitRegisterForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!--  编辑模态框-->
  <el-dialog v-model="dialogEditState" title="修改日常报销申请" width="700">
    <div>
      <el-form ref="formEditRef" :model="formEdit" label-width="120px" :rules="rules">
        <el-form-item prop="writedate" label="填报日期">
          <el-date-picker clearable
                          v-model="formEdit.writedate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择填报日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="department" label="部门">
          <el-select v-model="formEdit.department" placeholder="请选择部门" clearable >
            <el-option label="人事部" value="人事部"></el-option>
            <el-option label="后勤部" value="后勤部"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="reason"  label="报销事由">
          <el-input v-model="formEdit.reason" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item prop="money"  label="报销金额">
          <el-input v-model="formEdit.money" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="上传票据" prop="rill">
          <template #default="scope">
            <el-upload
                ref="uploadRef"
                :action="'http://localhost:9095/upload'"
                name="file"
                :show-file-list="false"
                :on-success="updateFiledUpload"
                :auto-upload="true"
                list-type="picture-card"
            >
              <img v-if="formEdit.rill" :src="formEdit.rill" class="avatar" style="width: 100px;height: 100px;border-radius: 5px"/>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit" >更新</el-button>
      </div>
    </template>
  </el-dialog>

</template>



<script setup>

import {ArrowRight} from "@element-plus/icons-vue";
import {Delete, DocumentChecked, Edit, Plus, Switch} from "@element-plus/icons";
import {onMounted, reactive, ref} from "vue";
import request from "@/utils/reimburse";
import {ElMessage, ElMessageBox, UploadProps, UploadUserFile} from "element-plus";
import axios from "axios";





const onSubmit = () => {
  console.log("onSubmit");
};

const  mallInfo=ref([])
onMounted(()=>{
  // 从SessionStorage取出数据
  let userstr = sessionStorage.getItem('loginUser')

  userInfo.username = JSON.parse(userstr).username
  getDailyapply();
})

//分页
const currentPage = ref(1)
const pageSize = ref(3)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const userInfo = reactive({
  'username' :null
})
const  blogInfo=ref([])
// 表格显示内容
const getDailyapply = () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    number: userInfo.username
    // 初始时不包含ID参数
  };
  // 如果填报日期不为空，则添加到查询参数中
  if (searchFormModel.writedate && searchFormModel.writedate.trim() !== '') {
    params.writedate = searchFormModel.writedate.trim();
  }
  // 如果部门不为空，则添加到查询参数中
  if (searchFormModel.department && searchFormModel.department.trim() !== '') {
    params.department = searchFormModel.department.trim();
  }
  // 如果报销事由不为空，则添加到查询参数中
  if (searchFormModel.reason && searchFormModel.reason.trim() !== '') {
    params.reason = searchFormModel.reason.trim();
  }
  // 如果报销金额不为空，则添加到查询参数中
  if (searchFormModel.money && searchFormModel.money.trim() !== '') {
    params.money = searchFormModel.money.trim();
  }
  // 如果上传票据不为空，则添加到查询参数中
  if (searchFormModel.rill && searchFormModel.rill.trim() !== '') {
    params.rill = searchFormModel.rill.trim();
  }
  // 如果审批状态不为空，则添加到查询参数中
  if (searchFormModel.state && searchFormModel.state.trim() !== '') {
    params.state = searchFormModel.state.trim();
  }
  request({
    url: '/dailyapply/selectByNum',
    method: 'get',
    params,
  }).then((req) => {
    console.log(req)
    if (200 == req.data.errorCode) {
      blogInfo.value = req.data.data.records.map(item => ({
        ...item,
      }));
      totals.value = req.data.data.total;
    }
  })
}
const handleCurrentChange = (page) => {
  currentPage.value = page
  getDailyapply()
}
const handleSizeChange = (size) => {
  pageSize.value = size
  getDailyapply()
}

//搜索
const searchFormRef=ref()
const searchFormModel=reactive({
  id:'',
  number:userInfo.username,
  writedate:'',
  department:'',
  reason:'',
  money:'',
  rill:'',
  state:''
})

// 定义下拉框选项
const departmentOptions = ref([
  {value: '', label: '全部'},
  { value: '人事部', label: '人事部' },
  { value: '后勤部', label: '后勤部' },
]);

const stateOptions = ref([
  {value: '', label: '全部'},
  { value: '0', label: '已拒绝' },
  { value: '1', label: '已通过' },
  { value: '2', label: '已驳回' },
  { value: '3', label: '已撤销' },
  { value: '4', label: '审批中' },
]);


const searchOnSubmit=()=>{
  getDailyapply()
}
const searchOnReset=()=>{
  searchFormModel.name=''
}

const rules=reactive({
  writedate: [
    { required: true, message: "填报日期不能为空", trigger: "blur"}
  ],
  department: [
    { required: true, message: "部门不能为空", trigger: "blur" }
  ],
  reason: [
    { required: true, message: "报销事由不能为空", trigger: "blur"}
  ],
  money: [
    { required: true, message: "报销金额不能为空", trigger: "change" }
  ],
  rill: [
    { required: true, message: "票据不能为空", trigger: "blur" }
  ]
})
///////////////////添加/////////////////////////
const dialogAddState = ref(false);
const formAddData = reactive({
  id:'',
  number:'',
  writedate:'',
  department:'',
  reason:'',
  money:'',
  rill:'',
  state:''
});
const formAdd = reactive({...formAddData});
const addressFormRef = ref(null); // 创建一个ref引用form
// 时间
const formatDate1=(value)=> {
  if (!value) {
    // 如果日期时间选择器的值为空，则不进行格式化
    formAdd.writedate = '';
    return;
  }
  // 将日期时间字符串转换为Date对象
  const date = new Date(value);
  // 获取年、月、日、小时、分钟和秒
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');

  // 组合成所需的格式
  formAdd.writedate = `${year}-${month}-${day} `;
}
const handleFiledUpload=(res)=>{
  console.log("图片:"+res)
  if (res != null){
    formAdd.rill=res.data
  }else {
    formAdd.rill=""
  }
}


// 提交表单
const submitRegisterForm = ()=>{
  if (formAddData.number == '' && formAddData.number.trim() == '') {
    formAdd.number = userInfo.username;
  }
  request({
    method:'post',
    url:'/dailyapply/add',
    params:formAdd
  }).then(req=>{
    if (200 == req.data.errorCode){
      ElMessage({
        type:'success',
        message:req.data.msg
      })
      Object.assign(formAdd , formAddData)
      formAdd.rill=""
      getDailyapply();
    }
  })
  dialogAddState.value=false;
}

const dialogAddOnReset = () => {
  formAdd.writedate=''
  formAdd.department=''
  formAdd.reason=''
  formAdd.money=''
  formAdd.rill=''
  formAdd.state=''
  // 关闭对话框
  dialogAddState.value=false;
}

///////////////////编辑/////////////////////////
const tableEditHandler = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)

  formEdit.id = rowData.id
  formEdit.number = rowData.number
  formEdit.writedate = rowData.writedate
  formEdit.department = rowData.department
  formEdit.reason = rowData.reason
  formEdit.money = rowData.money
  formEdit.rill = rowData.rill
  formEdit.state = rowData.state


  dialogEditState.value = true
}
// 新增表单引用
const formEditRef = ref()
const dialogEditState = ref(false)
const uploadRef = ref()
const imageUrl = ref('');
const updateFiledUpload=(res)=>{
  console.log("图片:"+res)
  imageUrl.value=res.date;
  formEdit.rill=res.data;
}
const dialogEditOnSubmit = () => {
  // 数据提交到服务器
  // 服务器端返回成功 ：清空表单，关闭对话框，更新表格内容
  request({
    method:'PUT',
    url:'/dailyapply/update',
    data:JSON.stringify(formEdit),
    headers: {'content-type': 'application/json;charset=UTF-8'}
  }).then(req=>{
    ElMessage({
      type:'success',
      message:req.data.msg
    })
    if (200==req.data.errorCode){
      getDailyapply()
    }
  })
  dialogEditState.value = false
}
// 新增表单初始化数据
const formEditData = {
  id:'',
  writedate:'',
  department:'',
  reason:'',
  money:'',
  rill:'',
  state:''
}
const dialogEditOnReset = () => {
  formEdit.writedate=''
  formEdit.department=''
  formEdit.reason=''
  formEdit.money=''
  formEdit.rill=''
  formEdit.state=''
  // 关闭对话框
  dialogEditState.value=false;
}
// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData})

//撤销
const tableDeleteHandler = (id) => {
  request({
    url: `/dailyapply/updateC?id=${id}`, // 如果后端通过 URL 参数接收 ID
    method: 'put',
    // 如果后端期望 ID 在请求体中，可以这样设置
    data: JSON.stringify({...formEdit, id }),
    headers: {'content-type': "application/json;charset=UTF-8"}
  }).then(req => {
    ElMessage({
      type: 'success',
      message: req.data.msg
    });
    if (200 === req.data.errorCode) {
      getDailyapply()
    }
  });
  dialogEditState.value = false;
};

</script>
<style scoped>
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>